#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import time
import commands
from yaml import load, dump

path = '/opt/fusionstack/etc/gbase.yml'


def parser(v=False):
    data = {}
    with open(path) as f:
        data = load(f)
    if v:
        dump(data)
    return data


def _derror(str1):
    sys.stderr.write("\x1b[1;31m%s\x1b[0m\n" % (str1))


def _exec_cmd(cmd, err=None, _exit=True, v=False):
    if v:
        print cmd
    (status, out) = commands.getstatusoutput(cmd)
    if status:
        _derror("status %d, err: %s" % (status, out))
        if err:
            _derror(err)
        if _exit:
            exit(int(status))
    print out


def _size2byte(size):
    if len(size) < 2:
        _derror("size err %s" % size)
        return 0

    sure = size[-2]
    if not str(sure).isdigit():
        _derror('unit in bBkKgGmMtT or None')
        return 0

    unit = size[-1]
    if str(unit).isdigit():
        return int(size)

    s = int(size[:-1])
    if unit in 'bB':
        return s
    elif unit in 'kK':
        return s * 1024
    elif unit in 'mM':
        return s * 1024 * 1024
    elif unit in 'gG':
        return s * 1024 * 1024 * 1024
    elif unit in 'tT':
        return s * 1024 * 1024 * 1024 * 1024
    else:
        _derror('unit in bBkKgGmMtT')
        return 0


def _byte2size(num, idx=0):
    unit = ['B', 'K', 'M', 'G', 'T']
    if (num / 1024 < 1) or (idx == len(unit) - 1):
        return str(round(num, 1)) + unit[idx]
    else:
        return _byte2size(num / 1024.0, idx + 1)


def _time_str(time_t):
    time_array = time.localtime(time_t)
    return time.strftime("%Y-%m-%d0", time_array)
